# -*- coding: utf-8 -*-

from rest_framework.decorators import action
from core.viewset import CustomModelViewSet
from core.response import JsonResponse
from rest_framework import status
from .models import Host
from .serializers import *
from .resources import *
from .filters import *


class HostViewSet(CustomModelViewSet):
    """
    主机管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = Host.objects.all()
    serializer_class = HostSerializer
    filterset_class = HostFilterSet
    import_resources = HostResouces
    export_resources = HostResouces

    # 自定义action: 申请主机
    @action(detail=False, methods=["GET"])
    def achieve(self, request, *args, **kwargs):
        try:
            filters = {
                "address": request.data.get("address"),
                "number": request.data.get("number"),
                "os": request.data.get("os"),
                "type": request.data.get("type"),
            }
            # 清除未指定或空值的过滤项
            filters = {k: v for k, v in filters.items() if v is not None}
            tags = request.data.get("tags")  # tags是一个标签列表
            if tags:
                filters["tags__name__in"] = tags.split(
                    ","
                )  # 调整此处根据你的模型实际情况
            host = HostManager.achieve_host(filters=filters)
            return JsonResponse(
                msg=f"Host {host.name} has been successfully allocated.",
                status=status.HTTP_200_OK,
                data=HostSerializer(host, many=False, request=request).data,
            )
        except ValueError as e:
            return JsonResponse(msg=str(e), status=status.HTTP_400_BAD_REQUEST)

    # 自定义action: 释放主机
    @action(detail=True, methods=["GET"])
    def release(self, request, pk=None, *args, **kwargs):
        try:
            released_host = HostManager.release_host(pk)
            return JsonResponse(
                msg=f"Host {released_host.name} has been successfully released.",
                status=status.HTTP_200_OK,
            )
        except ValueError as e:
            return JsonResponse(msg=str(e), status=status.HTTP_400_BAD_REQUEST)
